package com.study.service.Impl;

import com.study.enums.ResultCodeEnum;
import com.study.exception.MyException;
import com.study.mapper.AwardMapper;
import com.study.mapper.HeartbeatMapper;
import com.study.pojo.dto.Award;
import com.study.pojo.dto.Heartbeat;
import com.study.service.AwardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AwardServiceImpl implements AwardService {
    @Autowired
    private AwardMapper awardMapper;
    @Autowired
    private HeartbeatMapper heartbeatMapper;

    @Override
    public List<Award> queryAwardByUserId(Integer userId) {
        return awardMapper.queryAwardByUserId(userId);
    }

    @Override
    public Award queryAwardById(Integer id) {
        return awardMapper.queryAwardById(id);
    }

    @Override
    public int changeStatus(Integer id, String status) {
        if (awardMapper.changeStatus(id, status) == 0) {
            throw new MyException(ResultCodeEnum.CHANGE_FAILED);
        }
        return awardMapper.changeStatus(id, status);
    }

    @Override
    public int deleteAwardById(Integer id) {
        if (awardMapper.deleteAwardById(id) == 0) {
            throw new MyException(ResultCodeEnum.DELETE_FAILURE);
        }
        return awardMapper.deleteAwardById(id);
    }

    @Override
    public void insertAward(Award award) {
        if (awardMapper.insertAward(award) == 0) {
            throw new MyException(ResultCodeEnum.SAVE_FAILURE);
        }
    }

    @Override
    public Award getLastAward() {
        return awardMapper.getLastAward();
    }

    @Override
    public void getAward(Integer meId, Integer awardId, Integer price) {
        try {
            // 获取Ta给我添加的最后一条数据
            Heartbeat lastHeartbeat = heartbeatMapper.getLastHeartbeat(meId);
            // 查询奖品
            Award award = queryAwardById(awardId);
            // 添加一条兑换奖品的数据
            Heartbeat heartbeat = new Heartbeat(null, "「兑换奖品」", new Date(), price, "0",
                    lastHeartbeat.getTotalPoints() - price,
                    "在这天花费" + price + "积分兑换了「" + award.getAward() + "」 ",
                    lastHeartbeat.getUserId(), lastHeartbeat.getLoveId(), "true");
            heartbeatMapper.insertHeart(heartbeat);
            // 改变奖品状态为已领取未发奖
            changeStatus(awardId, "1");
        } catch (Exception e) {
            throw new MyException(ResultCodeEnum.RECEIVE_FAILURE);
        }
    }
}
